#include<bits/stdc++.h>
#define ll long long
#define pp push_back
#define endl '\n'
#define all(x) x.begin(),x.end()
#define ld long double
#define PI acos(-1)
#define sin(a) sin((a)*PI/180)
#define cos(a) cos((a)*PI/180)
#define ones(x) __builtin_popcountll(x)
//#define int ll
#define Drakon ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
unsigned long long inf = 1e10;
const double EPS = 1e-6;
const int MOD = 1000000007, N = 200005, LOG = 25, M = 2;
typedef array<array<int, M>, M> matrix;
ll gcd(ll x, ll y) {
return y ? gcd(y, x % y) : x;
}
ll lcm(ll a, ll b) {
return (a * b) / __gcd(a, b);
}
void solve() {
int n,m;
cin >> n >> m;
int arr[n][m],need[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> arr[i][j];
need[i][j] = i * m + j + 1;
}
}
int ans = 0;
for (int j = 0; j < m; ++j) {
vector<int>cur,want;
for (int i = 0; i < n; ++i) {
cur.pp(arr[i][j]);
want.pp(need[i][j]);
}
map<int,int>pos;
for(int i = 0; i < n; i ++){
pos[want[i]] = i;
}
int cycle[n];
memset(cycle,0,sizeof cycle);
for (int i = 0; i < n; ++i) {
if(pos.count(cur[i])){
int tmp = (i - pos[cur[i]] + n) % n;
cycle[tmp] ++;
}
}
int ret = 1e9;
for (int i = 0; i < n; ++i) {
ret = min(ret,n - cycle[i] + i);
}
ans += ret;
}
cout << ans << endl;
}
signed main() {
Drakon
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
1180A - Alex and a Rhombus | 445A - DZY Loves Chessboard |
1372A - Omkar and Completion | 159D - Palindrome pairs |
981B - Businessmen Problems | 1668A - Direction Change |
1667B - Optimal Partition | 1668B - Social Distance |
88B - Keyboard | 580B - Kefa and Company |
960A - Check the string | 1220A - Cards |
897A - Scarborough Fair | 1433B - Yet Another Bookshelf |
1283B - Candies Division | 1451B - Non-Substring Subsequence |
1408B - Arrays Sum | 1430A - Number of Apartments |
1475A - Odd Divisor | 1454B - Unique Bid Auction |
978C - Letters | 501B - Misha and Changing Handles |
1496A - Split it | 1666L - Labyrinth |
1294B - Collecting Packages | 1642B - Power Walking |
1424M - Ancient Language | 600C - Make Palindrome |
1669D - Colorful Stamp | 1669B - Triple |